package com.jay.media.music.ui

import android.Manifest
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.widget.Toolbar
import androidx.core.app.ActivityCompat
import androidx.navigation.NavController
import androidx.navigation.NavOptions
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.navigation.ui.setupWithNavController
import com.blankj.utilcode.util.SPUtils
import com.google.android.material.navigation.NavigationView
import com.jay.base.ui.BaseActivity
import com.jay.media.kit.DateUtils
import com.jay.media.kit.SPConstant
import com.jay.media.music.ui.base.BackHandleHelper
import com.jay.media.music.ui.databinding.ActivityLauncherBinding

/**
 * @author xuzhou
 * @email 1419982188@q.com
 * @date 2022/3/10
 */
class HomeActivity : BaseActivity() {

    private var appBarConfiguration: AppBarConfiguration? = null
    private lateinit var binding: ActivityLauncherBinding
    private lateinit var navController: NavController
    private lateinit var mediaPlayControls: View

    override fun onBackPressed() {
        if (!BackHandleHelper.handleBackPress(this)) {
            super.onBackPressed()
        }
    }

    override fun rootView(container: ViewGroup?): View? {
        binding = ActivityLauncherBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initView(view: View) {
        //申请权限
        if (ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(
                this,
                Manifest.permission.RECORD_AUDIO
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.RECORD_AUDIO
                ),
                1
            )
        }

        val navView: NavigationView = binding.navView
        navController = findNavController(R.id.nav_host_fragment_content_launcher)
        navView.setupWithNavController(navController)

        navController.addOnDestinationChangedListener { _, destination, _ ->
            Log.d(TAG, "initView() called with: destination = $destination")
            showOrHiddenMiniControls(
                destination.id == R.id.nav_home
            )
        }

        binding.navView.getHeaderView(0).findViewById<TextView>(R.id.timeTextView).text =
            DateUtils.getFormatDate()
        binding.navView.getHeaderView(0).findViewById<TextView>(R.id.nickTextView).text =
            String.format(
                getString(
                    R.string.nav_header_subtitle,
                    SPUtils.getInstance(SPConstant.SP_NAME_UI)
                        .getString(SPConstant.UIKeys.KEY_NICK_NAME, "J")
                )
            )

        appBarConfiguration = AppBarConfiguration(
            setOf(
                R.id.nav_home,
                R.id.nav_music,
                R.id.nav_file,
                R.id.nav_setting,
                R.id.nav_codec_setting
            ),
            binding.drawerLayout
        )
        setupDrawerLayout()

        mediaPlayControls =
            binding.appBarLauncher.contentLauncher.root.findViewById(R.id.media_play_controls)
    }

    override fun initData() {
        registerScreenLockReceiver()
    }

    override fun onDestroy() {
        unregisterScreenLockReceiver()
        super.onDestroy()
    }

    override fun onSupportNavigateUp(): Boolean {
        return navController.navigateUp(appBarConfiguration!!) || super.onSupportNavigateUp()
    }

    private fun setupDrawerLayout() {
        appBarConfiguration?.also {
            setupActionBarWithNavController(
                navController,
                it
            )
        }
    }

    fun navigate(resId: Int, bundle: Bundle?, navOptions: NavOptions?) {
        if (!navController.popBackStack(resId, false)) {
            navController.navigate(resId, bundle, navOptions)
        }
    }

    private fun showOrHiddenMiniControls(show: Boolean) {
        if (show) {
            val fragment = supportFragmentManager.findFragmentById(R.id.media_play_controls)
            fragment?.let {
                val transaction = supportFragmentManager.beginTransaction()
                transaction.show(fragment)
                transaction.setCustomAnimations(
                    R.anim.up_bottom_anim,
                    R.anim.bottom_up_anim,
                    R.anim.bottom_up_anim,
                    R.anim.up_bottom_anim
                )
                transaction.commit()
            }
        } else {
            val fragment = supportFragmentManager.findFragmentById(R.id.media_play_controls)
            fragment?.let {
                val transaction = supportFragmentManager.beginTransaction()
                transaction.hide(fragment)
                transaction.setCustomAnimations(
                    R.anim.up_bottom_anim,
                    R.anim.bottom_up_anim,
                    R.anim.bottom_up_anim,
                    R.anim.up_bottom_anim
                )
                transaction.commit()
            }
        }
    }

    fun setupToolbarNavBar(toolbar: Toolbar, menuIcon: Int? = null) {
        setSupportActionBar(toolbar)
        toolbar.setNavigationIcon(menuIcon ?: R.drawable.ic_menu)
        setupDrawerLayout()
    }

    fun updateToolbarTitle(title: String) {
        supportActionBar?.title = title
    }

    private fun registerScreenLockReceiver() {
        val intentFilter = IntentFilter()
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF)
        registerReceiver(mLockScreenReceiver, intentFilter)
    }

    private fun unregisterScreenLockReceiver() {
        unregisterReceiver(mLockScreenReceiver)
    }

    private var mLockScreenReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            Log.d(TAG, "onReceive() called with: context = $context, intent = $intent")
            if (Intent.ACTION_SCREEN_OFF == intent?.action) {
                var lockScreenIntent = Intent(this@HomeActivity, LockScreenActivity::class.java)
                lockScreenIntent.flags =
                    Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS or Intent.FLAG_ACTIVITY_NEW_TASK
                startActivity(lockScreenIntent)
            }
        }
    }
}